// Config.cpp
#include "Config.h"
#include <fstream>
#include <iostream>

bool Config::load(const std::string& config_path) {
    try {
        std::ifstream file(config_path);
        if (!file.is_open()) {
            std::cerr << "Failed to open config file: " << config_path << std::endl;
            return false;
        }
        
        json j;
        file >> j;
        
        // Redis配置
        if (j.contains("redis")) {
            auto redis = j["redis"];
            if (redis.contains("host")) redis_.host = redis["host"];
            if (redis.contains("port")) redis_.port = redis["port"];
            if (redis.contains("db")) redis_.db = redis["db"];
            if (redis.contains("password")) redis_.password = redis["password"];
            if (redis.contains("pool_size")) redis_.pool_size = redis["pool_size"];
        }
        
        // RocketMQ配置
        if (j.contains("rocketmq")) {
            auto mq = j["rocketmq"];
            if (mq.contains("name_server")) rocketmq_.name_server = mq["name_server"];
            if (mq.contains("consumer_group")) rocketmq_.consumer_group = mq["consumer_group"];
            if (mq.contains("topic")) rocketmq_.topic = mq["topic"];
            if (mq.contains("producer_group")) rocketmq_.producer_group = mq["producer_group"];
        }
        
        // 服务器配置
        if (j.contains("server")) {
            auto srv = j["server"];
            if (srv.contains("http_port")) server_.http_port = srv["http_port"];
            if (srv.contains("realm")) server_.realm = srv["realm"];
            if (srv.contains("password")) server_.password = srv["password"];
            if (srv.contains("keepalive_check_interval")) server_.keepalive_check_interval = srv["keepalive_check_interval"];
            if (srv.contains("thread_pool_size")) server_.thread_pool_size = srv["thread_pool_size"];
        }
        
        if (j.contains("server_reg_id")) {
            server_reg_id_ = j["server_reg_id"];
        }
        
        std::cout << "Config loaded successfully" << std::endl;
        return true;
        
    } catch (const std::exception& e) {
        std::cerr << "Error loading config: " << e.what() << std::endl;
        return false;
    }
}